import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_svg/svg.dart';
import 'package:get/get.dart';
import 'package:interview/components/app/app_prompt_overlay.dart';
import 'package:interview/components/page/page_menu_item.dart';
import 'package:interview/components/page/page_menu_overlay.dart';
import 'package:interview/config/app.enum.dart';
import 'package:interview/controller/navigation_controller.dart';
import 'package:interview/theme/app_colors.dart';
import 'package:interview/utils/logger.dart';
import 'package:interview/utils/permission_manager.dart';
import 'package:permission_handler/permission_handler.dart';

class HomeScan extends StatefulWidget {
  final AppColors theme;
  const HomeScan({super.key, required this.theme});

  @override
  State<HomeScan> createState() => _HomeScanState();
}

class _HomeScanState extends State<HomeScan> {
  final qrScannerChannel = MethodChannel('qr_scanner_channel');
  final navigation = Get.find<NavigationController>();

  Future<void> startQrScan(String mode) async {
    if(mode == "camera"){
      // 验证相机权限
      bool granted = await PermissionManager.requestPermissions(
        [Permission.camera],
      );

      if (!granted) {
        PermissionManager.openSettings(context, const Text('当前无摄像头权限，建议前往设置开通权限。') , widget.theme);
        return;
      }
    }
    

    try {
      // 调用原生方法，获取扫描结果
      final String result = await qrScannerChannel.invokeMethod('startQrScan', {"mode": mode});
      final Map<String, dynamic> questionParams = jsonDecode(result);

      // 字段校验
      final String? id = questionParams['id'];
      final List<dynamic>? ids = questionParams['ids']; // jsonDecode 解析为 dynamic List
      final int? typeId = questionParams['typeId'];
      final int? views = questionParams['views'];
      final String? tab = questionParams["tab"];


      // 校验各个字段是否满足要求
      if(
        id != null &&
        id.isNotEmpty &&
        ids != null &&
        ids.isNotEmpty &&
        ids.every((element) => element is String) && 
        typeId != null &&
        views != null &&
        tab != null
      ){
        // 跳转页面，传递参数
        navigation.pushWithAuth(
          '/questionpage',
          parameters: {
            "id": id,
            "ids": ids.cast<String>(), // 强制转换为 List<String>
            "typeId": typeId,
            "views": views,
            "tab":tab
          },
        );
      } else {
        // 如果数据校验不通过，记录日志
        Logger.info("扫描结果数据不完整或格式错误: $questionParams", tag: "startQrScan");
        AppPromptOverlay.show(context: context, message: "扫描结果无效，请重试");
      }
    } catch (e) {
      // AppPromptOverlay.show(context: context, message: "扫描失败，请联系工作人员");
      Logger.info("扫描失败 ${e} " , tag: "startQrScan");
    }
  }

  void _onTap(BuildContext context, AppColors theme) {
    PageMenuOverlay.show(
      theme: theme,
      context: context,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        mainAxisSize: MainAxisSize.min,
        children: [
          PageMenuItem(
            icon: CupertinoIcons.photo,
            theme: theme, 
            text: "相册", 
            onTap:  () {
              PageMenuOverlay.hide();
              startQrScan("gallery");
            }
          ),
          PageMenuItem(
            icon: CupertinoIcons.camera,
            theme: theme, 
            text: "相机", 
            onTap:  () {
              PageMenuOverlay.hide();
              startQrScan("camera");
            }
          ),
        ],
      ),
    );
  }
  void _onTapDown(TapDownDetails details) {
    PageMenuOverlay.setTapPosition(details);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap:() => _onTap(context , widget.theme),
      onTapDown: _onTapDown,
      child: SvgPicture.asset(
        '${AppEnumAssets.basePath}ic_home_scan.svg',
        width: 20,
        height: 18,
        colorFilter: ColorFilter.mode(
          widget.theme.contrastPure!, // 使用主题颜色
          BlendMode.srcIn, // 适配颜色覆盖
        ),
      )
    );
  }
}